package net.qhzw.vip.qiyu.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.config.WxPayConfiguration;
import net.qhzw.vip.qiyu.constant.CacheConstants;
import net.qhzw.vip.qiyu.entity.DtsCarRetreat;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.model.ForRetForm;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.DtsCarRetreatService;
import net.qhzw.vip.qiyu.service.PayService;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("dts/carRetreat")
@Api(tags = "退车申请管理")
@Slf4j
public class DtsCarRetreatController {

    @Autowired
    private DtsCarRetreatService dtsCarRetreatService;

    @Autowired
    private PayService wxPayService;

//    @Autowired
//    private WxPayService wxPayService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "退车费用分页列表查询")
    @GetMapping
    public JsonResult findByPage(Page<DtsCarRetreat> page, String idCard, String mobile, String realName, Long siteId) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        Map<String, Object> result = dtsCarRetreatService.findByPage(page, idCard, mobile, realName, siteId, shopId);
        return JsonResult.ok(result);
    }

    @ApiOperation(value = "退车费用明细")
    @PostMapping("retFeeLst")
    public JsonResult<Map<String, Object>> retFeeLst(@RequestBody ForRetForm forRetForm) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        Map<String, Object> result = dtsCarRetreatService.retFeeLst(forRetForm, shopId);
        return JsonResult.ok(result);
    }

    @ApiOperation(value = "退车支付回调")
    @PostMapping("pay/notify")
    public JsonResult payNotify(@RequestBody String xmlData) {
        //log.info("【退车支付回调】： {}", xmlData);
        WxPayOrderNotifyResult rs = WxPayOrderNotifyResult.fromXML(xmlData);
        String SubMchId = rs.getSubMchId();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setSubMchId(SubMchId);
        String outTradeNo = rs.getOutTradeNo();
        String transactionId = rs.getTransactionId();
        String appId = rs.getAppid();
        Object orderCache = redisTemplate.boundListOps(CacheConstants.CAR_RETREAT_ORDER_CACHE + ":" + outTradeNo).rightPop();
        if (orderCache != null) {
            WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
            dtsCarRetreatService.payNotify(outTradeNo, transactionId, appId);
        }

        return JsonResult.ok();
    }

    @ApiOperation(value = "退车退款回调")
    @RequestMapping("refund/notify")
    public JsonResult refundNotify(@RequestBody String xmlData) {
        //log.info("【退车退款回调】： {}", xmlData);
        WxPayOrderNotifyResult rs = WxPayOrderNotifyResult.fromXML(xmlData);
        String appId = rs.getAppid();
        String SubMchId = rs.getSubMchId();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(appId);
        wxPayConfig.setSubMchId(SubMchId);
        WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        try {
            WxPayRefundNotifyResult wxPayRefundNotifyResult = wxPayService.parseRefundNotifyResult(xmlData);
            //log.info("处理退款回调成功: {}", JSON.toJSONString(wxPayRefundNotifyResult));
            if (wxPayRefundNotifyResult.getReturnCode().equals("SUCCESS")) {
                WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
                String outRefundNo = reqInfo.getOutRefundNo();
                dtsCarRetreatService.refundNotify(outRefundNo);
            }
            return JsonResult.ok(wxPayRefundNotifyResult);
        } catch (WxPayException e) {
            e.printStackTrace();
            return JsonResult.fail(e.getReturnMsg() + "" + e.getCustomErrorMsg() + "" + e.getErrCodeDes());
        }

    }

    @ApiOperation(value = "退车申请")
    @PostMapping("appForRet")
    public JsonResult appForRet(@RequestBody ForRetForm forRetForm) {
        boolean isOK = dtsCarRetreatService.appForRet(forRetForm);
        if (isOK) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    @ApiOperation(value = "退车审核")
    @PostMapping("checkBack")
    public JsonResult rvwTheRet(@RequestBody Map<String, String> param) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        if (shopId == 1) {
            throw new ApiException("您是超级管理员, 不能审核该订单!");
        }
        Long id = Long.valueOf(param.get("id"));
        Byte status = Byte.valueOf(param.get("status"));
        String auditOpinion = param.get("auditOpinion");
        boolean isOK = dtsCarRetreatService.checkBack(id, status, auditOpinion, shopId);
        if (isOK) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "结算用户费用")
    @PostMapping("userRefund")
    public JsonResult userRefund(@RequestBody Map<String, String> param) {
        Long id = Long.valueOf(param.get("id"));
        String rfndCertificate = param.get("rfndCertificate");
        boolean isOK = dtsCarRetreatService.userRefund(id, rfndCertificate);
        if (isOK) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "退车费用清单导出")
    @GetMapping("export")
    public void export(HttpServletResponse response, String idCard, String mobile, String realName, Long siteId) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        dtsCarRetreatService.export(response, idCard, mobile, realName, siteId, shopId);
    }


    @ApiOperation(value = "导出退车欠款未结清记录")
    @GetMapping("export2")
    public void export2(HttpServletResponse response) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        dtsCarRetreatService.export2(response, shopId);
    }


    @RequestMapping("rvwRejected/refund/notify")
    public JsonResult rvwRejected(@RequestBody String xmlData) {
        //log.info("【审核驳回回调】： {}", xmlData);
        WxPayRefundNotifyResult wxPayRefundNotifyResult = null;
        try {
            // wxPayRefundNotifyResult = wxPayService.parseRefundNotifyResult(xmlData);
            wxPayRefundNotifyResult = null;
            if (wxPayRefundNotifyResult.getReturnCode().equals("SUCCESS")) {
                WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
                String outRefundNo = reqInfo.getOutRefundNo();
                log.info("【审核驳回回调 outRefundNo: {}】", outRefundNo);
            }
        } catch (Exception e) {
            log.error("退款失败，失败信息:{}", e);
        }
        return JsonResult.ok();
    }

    @GetMapping("inspect/{carRentalId}")
    public JsonResult inspect(@PathVariable Long carRentalId) {
        boolean isok = dtsCarRetreatService.inspect(carRentalId);
        if (isok) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


}
